package com.axend.vetwavve.fragment

import android.graphics.Bitmap
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import com.axend.lib_base.base.fragment.BaseVVDInfraredCameraFragment
import com.axend.lib_base.base.vm.BaseViewModel
import com.axend.lib_base.ext.clearAllFragments
import com.axend.lib_base.ext.preloadFragment
import com.axend.lib_base.ext.replaceFragment
import com.axend.lib_base.ext.runOnUIThread
import com.axend.lib_base.ext.showPreloadFragment
import com.axend.lib_base.utils.ScreenAutoAdapter
import com.axend.lib_base.view.RectangleView
import com.axend.lib_room.entity.PetInfoEntity
import com.axend.lib_service.Constant.designSize
import com.axend.vetwavve.activity.MainActivity
import com.axend.vetwavve.databinding.FragmentWaitControlBinding
import com.axend.vetwavve.fragment.startmonitoring.StartMonitoringFragment
import com.guide.zx03c.GuideInterface
import com.guide.zx03c.UsbStatusInterface
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @description开始监控页
 * @author admins
 * @time 2024/6/17 15:32
 */
class WaitControlFragment :
    BaseVVDInfraredCameraFragment<BaseViewModel, FragmentWaitControlBinding>(),
    UsbStatusInterface, GuideInterface.ImageCallBackInterface {

    private val highCrossWidth = 120
    private val highCrossHeight = 120

    companion object {
        fun newInstance(petInfoEntity: PetInfoEntity): WaitControlFragment {
            return WaitControlFragment().apply {
                arguments = Bundle().apply {
                    if (petInfoEntity != null)
                        putParcelable(AddOrEditRecordFragment.ARGUMENT_PET_INFO, petInfoEntity)

                }
            }
        }
    }

    override fun getBindingVariable(): Int = 0
    override fun setScale(): Int {
        return resources.getDimension(com.axend.lib_base.R.dimen.wait_control_width).toInt()
    }

    override fun setUsbStatusInterface(): UsbStatusInterface {
        return this
    }

    override fun setImageCallBackInterface(): GuideInterface.ImageCallBackInterface {
        return this
    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        val petInfoEntity = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getParcelable(
                AddOrEditRecordFragment.ARGUMENT_PET_INFO,
                PetInfoEntity::class.java
            )
        } else {
            arguments?.getParcelable(AddOrEditRecordFragment.ARGUMENT_PET_INFO)
        }
        rectangleView = RectangleView(requireContext(), Color.WHITE)
        /*将红外视图添加到父布局中*/
        mBinding.flContent.addView(mIrSurfaceView)

        irSurfaceViewWidth =
            resources.getDimension(com.axend.lib_base.R.dimen.wait_control_width)
        irSurfaceViewHeight =
            resources.getDimension(com.axend.lib_base.R.dimen.wait_control_height)


        titleBarBinding.ivBack.setOnClickListener {
            (requireActivity() as? MainActivity)?.onBack()
        }
        mBinding.llWaitControl.setOnClickListener {
            mBinding.tvNext.setText(com.axend.lib_base.R.string.app_wait_control_loading)
            mBinding.loadProgressBar.visibility = View.VISIBLE
            CoroutineScope(Dispatchers.Main).launch {
                delay(3000)
                replaceFragment(
                    requireActivity(),
                    (requireActivity() as MainActivity).getFragmentContainerId(),
                    StartMonitoringFragment.newInstance(petInfoEntity),
                    this@WaitControlFragment,
                    null,
                    true
                )
//                stopGetImage()
//                guideInterface?.guideCoreExit()
//                guideInterface=null
//                delay(2000)
//                val nextFragment = StartMonitoringFragment.newInstance(petInfoEntity)
//                preloadFragment(
//                    requireActivity(),
//                    (requireActivity() as MainActivity).getFragmentContainerId(),
//                    nextFragment,
//                    null
//                )
//
//                CoroutineScope(Dispatchers.Main).launch {
//                    delay(4000)
//                    showPreloadFragment(
//                        requireActivity(),
//                        nextFragment,
//                        this@WaitControlFragment,
//                        null,
//                    )
//                }
            }

        }


    }


    override fun usbConnect() {
    }

    override fun usbDisConnect() {
//        toast(getString(com.axend.lib_base.R.string.app_device_disconnected))
    }

    override fun callBackOneFrameBitmap(p0: Bitmap?, p1: ShortArray?) {
        mIrSurfaceView.doDraw(p0, guideInterface?.shutterStatus!!)
        count++
        if (count % FRAME == 0) {
            val maxY16 = getMaxY16(p1!!)
            Log.v("GUIDE", "maxY16=$maxY16")
            val (rawWidth, rawHeight) = when (rotateType) {
                1, 3 -> Pair(SRC_WIDTH, SRC_HEIGHT)
                else -> Pair(SRC_HEIGHT, SRC_WIDTH)
            }
            mY16Frame = p1
            getOneRectTemp()
            runOnUIThread {
                mBinding.flDisplay.removeView(mHighCrossView)

                val scale = irSurfaceViewWidth / y16W
//                val lp = FrameLayout.LayoutParams(highCrossWidth, highCrossHeight).apply {
//                    leftMargin = (maxIndex % rawWidth * scale - highCrossWidth / 2).toInt()
//                    topMargin = (maxIndex / rawWidth * scale - highCrossHeight / 2).toInt()
//                }
                val lp = FrameLayout.LayoutParams(highCrossWidth, highCrossHeight).apply {
                    leftMargin = ((maxX * scale) - highCrossWidth / 2).toInt()
                    topMargin = ((maxY * scale) - highCrossHeight / 2).toInt()
                }

                mBinding.flDisplay.addView(mHighCrossView, lp)

//                /*绘制矩形到Layout上*/
//                mBinding.flDisplay.removeView(rectangleView)
//                rectangleView.setRectangleProperties(
//                    centerX,
//                    centerY,
//                    radius * 2,
//                    radius * 2,
//                    scale
//                )
//                mBinding.flDisplay.addView(rectangleView)
            }

            count = 0
        }
    }


    override fun onResume() {
        super.onResume()
        ScreenAutoAdapter.match(requireActivity(), designSize)
        startGetImage()
        mBinding.tvNext.setText(com.axend.lib_base.R.string.app_start_monitoring)
        mBinding.loadProgressBar.visibility = View.GONE
    }


    override fun onPause() {
        super.onPause()
        try {
            stopGetImage()
        }catch (e:Exception){
            Log.e("WaitControlFragment",e.message?:"")
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        guideInterface?.guideCoreExit()
    }


}